<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>知识片段查看器</title>
    <!-- 引入样式库 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/styles/github.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        
        .qa-item {
            margin-bottom: 20px;
            border: 1px solid #eee;
            border-radius: 5px;
            padding: 15px;
            background-color: #fff;
        }
        
        .qa-item:hover {
            border-color: #ccc;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        .qa-question {
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .qa-answer {
            margin-bottom: 10px;
            white-space: pre-wrap;
        }
        
        .edit-area {
            display: none;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #ddd;
        }
        
        .filter-panel {
            margin-bottom: 20px;
        }
        
        .metadata-panel {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <header class="py-3 mb-4 border-bottom bg-light">
            <div class="container d-flex justify-content-between align-items-center">
                <h1 class="fs-4">知识片段查看器</h1>
                <a href="/" class="btn btn-outline-secondary">返回主页</a>
            </div>
        </header>

        <main class="container">
            <!-- 元数据和文档信息 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>文档信息</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="documentName" class="form-label">文档名称</label>
                                <input type="text" class="form-control" id="documentName" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="sourceName" class="form-label">知识来源</label>
                                <input type="text" class="form-control" id="sourceName" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="systemName" class="form-label">系统名称</label>
                                <input type="text" class="form-control" id="systemName" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="totalQA" class="form-label">问答对数量</label>
                                <input type="text" class="form-control" id="totalQA" readonly>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 过滤和搜索 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>搜索与过滤</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="input-group mb-3">
                                <input type="text" class="form-control" id="searchInput" placeholder="搜索问题或答案...">
                                <button class="btn btn-outline-secondary" type="button" id="searchButton">搜索</button>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="d-flex justify-content-end">
                                <button class="btn btn-primary" id="downloadQABtn">下载 JSON</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 加载指示器 -->
            <div id="loadingIndicator" class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-3">加载知识片段...</p>
            </div>

            <!-- 问答列表 -->
            <div id="qaList" class="mt-4">
                <!-- QA 列表将在这里动态生成 -->
            </div>
        </main>

        <footer class="py-3 mt-4 border-top">
            <div class="container text-center">
                <p class="text-muted">文档转换知识片段工具 &copy; 2025</p>
            </div>
        </footer>
    </div>

    <!-- 引入脚本库 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked@5.0.0/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/lib/highlight.min.js"></script>
    <script>
        // 获取文件名
        const filename = "{{ filename }}";
        let qaData = null;
        
        // 页面加载完成后获取QA数据
        document.addEventListener('DOMContentLoaded', async () => {
            try {
                const response = await fetch(`/get_qa_file/${filename}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                qaData = await response.json();
                
                // 更新文档信息
                document.getElementById('documentName').value = qaData.original_file || filename;
                document.getElementById('systemName').value = qaData.system_name || '';
                document.getElementById('sourceName').value = qaData.source_name || '';
                document.getElementById('totalQA').value = qaData.qa_pairs.length;
                
                // 渲染QA列表
                renderQAList(qaData.qa_pairs);
                
                // 隐藏加载指示器
                document.getElementById('loadingIndicator').style.display = 'none';
                
                // 初始化事件监听
                initEventListeners();
            } catch (error) {
                console.error('Failed to load QA data:', error);
                document.getElementById('loadingIndicator').innerHTML = `
                    <div class="alert alert-danger">
                        加载失败：${error.message}
                    </div>
                `;
            }
        });
        
        // 渲染QA列表
        function renderQAList(qaPairs) {
            const qaListElement = document.getElementById('qaList');
            
            // 清空现有内容
            qaListElement.innerHTML = '';
            
            // 添加每个QA
            qaPairs.forEach((qa, index) => {
                const qaElement = document.createElement('div');
                qaElement.className = 'qa-item';
                qaElement.dataset.index = index;
                
                qaElement.innerHTML = `
                    <div class="qa-question">${index + 1}. Q: ${escapeHtml(qa.question)}</div>
                    <div class="qa-answer">A: ${escapeHtml(qa.answer)}</div>
                    <div class="qa-controls">
                        <button class="btn btn-sm btn-outline-primary edit-qa">编辑</button>
                        <button class="btn btn-sm btn-outline-danger delete-qa">删除</button>
                    </div>
                    <div class="edit-area">
                        <div class="mb-3">
                            <label class="form-label">问题</label>
                            <input type="text" class="form-control edit-question" value="${escapeHtml(qa.question)}">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">答案</label>
                            <textarea class="form-control edit-answer" rows="5">${escapeHtml(qa.answer)}</textarea>
                        </div>
                        <div class="text-end">
                            <button class="btn btn-sm btn-secondary cancel-edit">取消</button>
                            <button class="btn btn-sm btn-success save-edit">保存</button>
                        </div>
                    </div>
                `;
                
                qaListElement.appendChild(qaElement);
            });
            
            // 如果没有QA，显示提示
            if (qaPairs.length === 0) {
                qaListElement.innerHTML = `
                    <div class="alert alert-info">
                        没有找到知识片段数据
                    </div>
                `;
            }
        }
        
        // 初始化事件监听
        function initEventListeners() {
            // 编辑按钮
            document.querySelectorAll('.edit-qa').forEach(button => {
                button.addEventListener('click', function() {
                    const qaItem = this.closest('.qa-item');
                    qaItem.querySelector('.edit-area').style.display = 'block';
                    this.style.display = 'none';
                });
            });
            
            // 取消编辑按钮
            document.querySelectorAll('.cancel-edit').forEach(button => {
                button.addEventListener('click', function() {
                    const qaItem = this.closest('.qa-item');
                    qaItem.querySelector('.edit-area').style.display = 'none';
                    qaItem.querySelector('.edit-qa').style.display = 'inline-block';
                });
            });
            
            // 保存编辑按钮
            document.querySelectorAll('.save-edit').forEach(button => {
                button.addEventListener('click', function() {
                    const qaItem = this.closest('.qa-item');
                    const index = parseInt(qaItem.dataset.index);
                    
                    // 获取编辑内容
                    const question = qaItem.querySelector('.edit-question').value;
                    const answer = qaItem.querySelector('.edit-answer').value;
                    
                    // 更新数据
                    qaData.qa_pairs[index].question = question;
                    qaData.qa_pairs[index].answer = answer;
                    
                    // 更新UI
                    qaItem.querySelector('.qa-question').textContent = `${index + 1}. Q: ${question}`;
                    qaItem.querySelector('.qa-answer').textContent = `A: ${answer}`;
                    
                    // 隐藏编辑区域
                    qaItem.querySelector('.edit-area').style.display = 'none';
                    qaItem.querySelector('.edit-qa').style.display = 'inline-block';
                    
                    // TODO: 发送更新到服务器
                });
            });
            
            // 删除按钮
            document.querySelectorAll('.delete-qa').forEach(button => {
                button.addEventListener('click', function() {
                    if (confirm('确定要删除这个问答对吗？')) {
                        const qaItem = this.closest('.qa-item');
                        const index = parseInt(qaItem.dataset.index);
                        
                        // 从数据中删除
                        qaData.qa_pairs.splice(index, 1);
                        
                        // 更新总数
                        document.getElementById('totalQA').value = qaData.qa_pairs.length;
                        
                        // 重新渲染列表
                        renderQAList(qaData.qa_pairs);
                        
                        // 重新绑定事件
                        initEventListeners();
                        
                        // TODO: 发送更新到服务器
                    }
                });
            });
            
            // 搜索按钮
            document.getElementById('searchButton').addEventListener('click', function() {
                const searchText = document.getElementById('searchInput').value.toLowerCase();
                
                if (!searchText) {
                    renderQAList(qaData.qa_pairs);
                    initEventListeners();
                    return;
                }
                
                // 过滤结果
                const filteredQA = qaData.qa_pairs.filter(qa => 
                    qa.question.toLowerCase().includes(searchText) || 
                    qa.answer.toLowerCase().includes(searchText)
                );
                
                renderQAList(filteredQA);
                initEventListeners();
            });
            
            // 下载按钮
            document.getElementById('downloadQABtn').addEventListener('click', function() {
                const dataStr = JSON.stringify(qaData, null, 2);
                const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
                
                const exportFileName = `${filename.replace('.json', '')}_edited.json`;
                
                const linkElement = document.createElement('a');
                linkElement.setAttribute('href', dataUri);
                linkElement.setAttribute('download', exportFileName);
                linkElement.click();
            });
        }
        
        // HTML转义函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html> 